<?php
class MySQL {

    private static $instance;

    private function __construct() {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_DATABASE;
        $this->PDO = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    }

    public static function getInstance() {
        if(!self::$instance) {
            self::$instance = new MySQL();
        }
        return self::$instance;
    }

    private function query() {
        $args = func_get_args();
        $args = array_shift($args);
        $sql = array_shift($args);
        $query = vsprintf($sql, $args);

        $sth = $this->PDO->prepare($query);
        if(!$sth) {
            die(var_dump($this->PDO->errorInfo()));
        }
        if(!$sth->execute()) {
            die(var_dump($sth->errorInfo()));
        }
        if(strpos(strtolower($query), 'select') !== FALSE) {
            return $sth;
        } elseif(strpos(strtolower($query), 'insert') !== FALSE) {
            $id = $this->PDO->lastInsertId();
            return ($id ? $id : TRUE);
        } else {
            return TRUE;
        }
    }

    public function fquery() {
        $sth = $this->query(func_get_args());
        if(is_object($sth)) {
            return $sth->fetchAll(PDO::FETCH_ASSOC);
        } else {
            return $sth;
        }
    }

    public function fetch_single() {
        $sth = $this->query(func_get_args());
        if(is_object($sth)) {
            return $sth->fetch(PDO::FETCH_ASSOC);
        } else {
            return $sth;
        }
    }

    public function fetch_value() {
        $sth = $this->query(func_get_args());
        if(is_object($sth)) {
            $ret = $sth->fetch(PDO::FETCH_NUM);
            if($ret) {
                return $ret[0];
            } else {
                return FALSE;
            }
        } else {
            return $sth;
        }
    }
}
?>
